// ts转js
import typescript from "@rollup/plugin-typescript";
// 解析导入的依赖模块路径，以便 Rollup 能够正确找到依赖模块
import resolve from "@rollup/plugin-node-resolve";
// 将 CommonJS 模块转为 ES6 模块，使其能够被 Rollup 处理和打包
import commonjs from "@rollup/plugin-commonjs";
// 删除注释，压缩代码
import terser from "@rollup/plugin-terser";
// 生成dts文件
import dts from "rollup-plugin-dts";
import fs from "fs";

// 忽略循环引用警告
const onwarn = (msg, warn) => {
    if (!/Circular/.test(msg)) {
        warn(msg);
    }
};

let input = {};
let external = [];
// 遍历所有包
const packages = ["compiler-core", "reactivity", "runtime-core", "runtime-dom", "shared", "vue"];
packages.forEach((name) => {
    // 收集入口
    input[name] = `./packages/${name}/src/index.ts`;
    // 收集依赖
    const pkg = JSON.parse(fs.readFileSync(`packages/${name}/package.json`, "utf8"));
    if (pkg.dependencies) {
        external = external.concat(Object.keys(pkg.dependencies));
    }
});

export default [
    // 打包到npm
    {
        input,
        output: [
            {
                dir: "packages",
                entryFileNames: `[name]/dist/[name].esm.js`,
                format: "es",
            },
            {
                dir: "packages",
                entryFileNames: `[name]/dist/[name].cjs.js`,
                format: "cjs",
            },
        ],
        // 设置不需要打包进来的包
        external,
        plugins: [resolve(), commonjs(), typescript()],
        onwarn,
    },
    // 生成dts文件
    {
        input,
        output: [
            {
                dir: "packages",
                entryFileNames: `[name]/dist/[name].d.ts`,
                format: "es",
            },
        ],
        plugins: [dts()],
    },
    // 打包到浏览器
    {
        input: "./packages/vue/src/index.ts",
        output: [
            {
                file: `packages/vue/dist/vue.global-esm.js`,
                format: "es",
                sourcemap: true,
            },
            {
                name: "vue",
                file: `packages/vue/dist/vue.global.js`,
                format: "iife",
                sourcemap: true,
            },
        ],
        plugins: [resolve(), commonjs(), typescript(), terser()],
        onwarn,
    },
];